<template>
    <div v-if="!userStore.isLoggedIn" class="login-prompt-overlay">
        <p>请先登录以继续</p>
        <el-button type="primary" @click="goToLogin">前往登录</el-button>
    </div>
    <div class="left-menu-container" :class="{ collapsed: isCollapsed }">
        <!-- 顶部区域：LOGO + 收缩按钮 -->
        <div class="menu-header">
            <span v-show="!isCollapsed" class="logo-text">慧心学院</span>
            <el-button icon="ArrowLeft" circle size="small" @click="toggleCollapse" />
        </div>

        <!-- 菜单列表 -->
        <el-menu 
            :default-active="activeIndex"
            router 
            class="el-menu-vertical" 
            :collapse="isCollapsed"
            :collapse-transition="false"
            background-color="#2c3e50"
            text-color="#fff"
            active-text-color="#409eff"
            :default-openeds="openMenuIds"
        >
            <!-- 动态菜单 -->
            <template v-if="menuList.length > 0">
                <template v-for="menu in menuList" :key="menu.id">
                    <!-- 无子菜单 -->
                    <el-menu-item v-if="!menu.children || menu.children.length === 0" :index="menu.url">
                        <el-icon v-if="menu.icon">
                            <component :is="getIconComponent(menu.icon)" />
                        </el-icon>
                        <span>{{ menu.name }}</span>
                    </el-menu-item>
                    <!-- 有子菜单 -->
                    <el-sub-menu v-else :index="String(menu.id)">
                        <template #title>
                            <el-icon v-if="menu.icon">
                                <component :is="getIconComponent(menu.icon)" />
                            </el-icon>
                            <span>{{ menu.name }}</span>
                        </template>
                        <el-menu-item 
                            v-for="child in menu.children" 
                            :key="child.id" 
                            :index="child.url"
                        >
                            <span>{{ child.name }}</span>
                        </el-menu-item>
                    </el-sub-menu>
                </template>
            </template>
            <!-- 加载状态 -->
            <template v-else-if="loading">
                <el-menu-item index="">
                    <el-skeleton animated />
                </el-menu-item>
            </template>
            <!-- 默认菜单 -->
            <template v-else>
                <el-menu-item index="/dashboard">
                    <el-icon>
                        <HomeFilled />
                    </el-icon>
                    <span>仪表盘</span>
                </el-menu-item>
                <el-menu-item index="/user">
                    <el-icon>
                        <User />
                    </el-icon>
                    <span>用户管理</span>
                </el-menu-item>
                <el-menu-item index="/course">
                    <el-icon>
                        <Document />
                    </el-icon>
                    <span>课程管理</span>
                </el-menu-item>
            </template>
        </el-menu>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
    HomeFilled,
    ChatLineRound,
    Grid,
    Document,
    User,
    ArrowLeft,
    Setting,
    Monitor,
    Management,
    Database,
    FileText,
    VideoPlay,
    Category,
    Menu,
    Message
} from '@element-plus/icons-vue'
import { user } from '@/stores/user.js'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const userStore = user()

// 控制是否折叠菜单
const isCollapsed = ref(false)
// 菜单列表
const menuList = ref([])
// 加载状态
const loading = ref(false)

// 激活的菜单项 - 增强高亮逻辑
const activeIndex = computed(() => {
    // 确保route.path存在，避免出现undefined
    const currentPath = route.path || '/admin/home'
    
    // 检查是否能在菜单列表中找到精确匹配
    let matchedPath = findMatchedPath(currentPath)
    
    // 如果没有精确匹配，回退到当前路径或默认路径
    return matchedPath || currentPath
})

// 查找匹配的菜单项路径
const findMatchedPath = (currentPath) => {
    // 首先检查一级菜单项
    for (const menu of menuList.value) {
        if (menu.url && currentPath === menu.url) {
            return menu.url
        }
        
        // 然后检查子菜单项
        if (Array.isArray(menu.children)) {
            for (const child of menu.children) {
                if (child.url && currentPath === child.url) {
                    return child.url
                }
            }
        }
    }
    
    // 如果没有精确匹配，尝试模糊匹配（例如 /admin/users/123 匹配到 /admin/users）
    const pathSegments = currentPath.split('/').filter(Boolean)
    for (let i = pathSegments.length; i > 0; i--) {
        const partialPath = '/' + pathSegments.slice(0, i).join('/')
        const matchedMenu = findExactMatch(partialPath)
        if (matchedMenu) return partialPath
    }
    
    return null
}

// 精确查找匹配路径
const findExactMatch = (path) => {
    for (const menu of menuList.value) {
        if (menu.url === path) return menu
        
        if (Array.isArray(menu.children)) {
            for (const child of menu.children) {
                if (child.url === path) return child
            }
        }
    }
    return null
}

// 计算需要展开的菜单 ID 列表 - 增强版本
const openMenuIds = computed(() => {
    // 确保menuList存在
    const menus = menuList.value || []
    const currentPath = route.path || '/admin/home'
    const openIds = []
    
    // 查找当前路径应该展开哪些菜单
    for (const menu of menus) {
        // 检查当前路径是否匹配一级菜单
        if (menu.url && currentPath === menu.url) {
            continue // 一级菜单不需要展开父菜单
        }
        
        // 检查子菜单是否匹配当前路径
        if (Array.isArray(menu.children)) {
            for (const child of menu.children) {
                if (child.url === currentPath) {
                    openIds.push(String(menu.id))
                    break
                }
                
                // 支持模糊匹配子菜单（例如 /admin/users/123 应该展开用户管理菜单）
                if (child.url && currentPath.startsWith(child.url + '/')) {
                    openIds.push(String(menu.id))
                    break
                }
            }
        }
        
        // 支持模糊匹配一级菜单（例如 /admin/settings/profile 应该匹配 /admin/settings）
        if (menu.url && currentPath.startsWith(menu.url + '/') && !openIds.includes(String(menu.id))) {
            // 如果是多级嵌套菜单，这里可能需要更复杂的逻辑
            // 但目前先保持简单，只处理一级菜单的模糊匹配
        }
    }
    
    return openIds
})

// 图标组件映射
const iconMap = {
    HomeFilled,
    ChatLineRound,
    Grid,
    Document,
    User,
    Setting,
    Monitor,
    Management,
    Database,
    FileText,
    VideoPlay,
    Category,
    Menu,
    Message
}

// 获取图标组件
const getIconComponent = (iconName) => {
    return iconMap[iconName] || HomeFilled
}

// 切换折叠状态
const toggleCollapse = () => {
    isCollapsed.value = !isCollapsed.value
}

// 跳转到登录页
const goToLogin = () => {
    router.push('/auth/login')
}

// 获取菜单列表 - 参照Header.vue的修复方案优化
const fetchMenuList = async () => {
    // 增加健壮性检查
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.roleId) {
        console.warn('用户未登录或角色信息不完整，无法获取菜单')
        return
    }
    
    loading.value = true
    try {
        console.debug('正在获取管理端菜单，用户角色ID:', userStore.userInfo.roleId)
        const response = await axios.get(process.env.VUE_APP_URL + '/menu/get', {
            params: {
                roleId: userStore.userInfo.roleId,
                type: 2, // 2表示后台管理菜单
                pageId: 1
            }
        })

        console.debug('菜单获取响应:', response.data)
        if (response.data.code === 100) {
            // 确保返回的数据是数组格式
            menuList.value = Array.isArray(response.data.data) ? response.data.data : []
            console.debug('管理端菜单列表已加载，数量:', menuList.value.length)
        } else {
            console.warn('获取菜单返回非成功状态:', response.data.code)
            menuList.value = []
        }
    } catch (err) {
        console.error('获取管理端菜单失败:', err)
        // 出错时使用默认菜单，确保用户体验不中断
        menuList.value = [
            { id: 1, name: '仪表盘', url: '/admin/home', icon: 'HomeFilled', children: [] },
            { id: 2, name: '用户管理', url: '/admin/users', icon: 'User', children: [] },
            { id: 3, name: '课程管理', url: '/admin/courses', icon: 'Document', children: [] },
            { id: 4, name: '菜单管理', url: '/admin/menus', icon: 'Menu', children: [] },
            { id: 5, name: '角色管理', url: '/admin/roles', icon: 'Management', children: [] }
        ]
    } finally {
        loading.value = false
    }
}

// 监听登录状态变化 - 增强处理逻辑
watch(
    () => [userStore.isLoggedIn, userStore.userInfo?.roleId],
    ([isLoggedIn, roleId]) => {
        console.debug('登录状态变化，已登录:', isLoggedIn, '角色ID:', roleId)
        if (isLoggedIn && roleId === 2) { // 确保只有管理员角色才能获取管理端菜单
            fetchMenuList()
        } else {
            menuList.value = []
        }
    },
    { deep: true, immediate: true } // 增加深度监听和立即执行
)

// 监听路由变化，确保菜单能正确高亮和展开 - 增强版本
watch(
    () => route.path,
    (newPath) => {
        console.debug('路由变化，当前路径:', newPath)
        // 路由变化时强制更新activeIndex
        // 由于使用了computed属性，这里不需要手动更新，但可以添加额外逻辑
        
        // 确保菜单在路由变化时能正确展开
        // 可能需要使用nextTick确保DOM已更新
    }
)

// 组件挂载时初始化
onMounted(async () => {
    console.debug('LeftMenu组件挂载，检查用户登录状态')
    
    // 确保只在管理员角色下加载管理端菜单
    if (userStore.isLoggedIn && userStore.userInfo?.roleId === 2) {
        await fetchMenuList()
        
        // 使用nextTick确保DOM完全更新后再处理菜单高亮
        await nextTick()
        console.debug('DOM已更新，确保菜单高亮状态正确')
        
        // 确保当前路径能正确匹配菜单项
        console.debug('当前路径:', route.path)
        console.debug('激活的菜单项:', activeIndex.value)
        console.debug('需要展开的菜单ID:', openMenuIds.value)
    }
})
</script>

<style lang="scss" scoped>
.login-prompt-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(44, 62, 80, 0.9);
    z-index: 999;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 4px;

    p {
        margin-bottom: 1rem;
        font-size: 16px;
        color: #fff;
    }
}

.left-menu-container {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 15%;
    min-width: 200px;
    background-color: #2c3e50;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    transition: width 0.3s ease;
    z-index: 100;

    &.collapsed {
        width: 64px;
    }

    .menu-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 1rem;
        height: 60px;
        box-sizing: border-box;
        background-color: #1a2530;
        border-bottom: 1px solid #34495e;

        .logo-text {
            font-size: 18px;
            font-weight: bold;
            color: #fff;
        }
    }

    .el-menu-vertical {
        flex: 1;
        border-right: none;
        height: calc(100% - 60px);
        background-color: #2c3e50;
        overflow-y: auto;

        // 自定义滚动条样式
        &::-webkit-scrollbar {
            width: 4px;
        }

        &::-webkit-scrollbar-track {
            background: #1a2530;
        }

        &::-webkit-scrollbar-thumb {
            background: #34495e;
            border-radius: 2px;
        }

        &::-webkit-scrollbar-thumb:hover {
            background: #4a6077;
        }
    }

    // 移除user-profile样式
}
</style>